#!/usr/bin/env python
# encoding: utf-8

import ssl

try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    pass
else:
    ssl._create_default_https_context = _create_unverified_https_context

import logging
import requests
from suds.client import Client
from suds.transport.http import Reply
from suds.transport.https import HttpAuthenticated

logger = logging.getLogger('sendsms')


class RequestsTransport(HttpAuthenticated):

    def __init__(self, **kwargs):
        self.cert = None
        HttpAuthenticated.__init__(self, **kwargs)

    def send(self, request):
        self.addcredentials(request)
        resp = requests.post(
            request.url,
            data=request.message,
            headers=request.headers,
            cert=self.cert,
            verify=False
        )
        result = Reply(resp.status_code, resp.headers, resp.content)
        return result


class SmsXuanwu(object):

    WSDLFILE = 'https://mos.wxchina.com:8099/Service/WebService.asmx?wsdl'
    SEND_TYPE = '0'  # 发送类型，0位群发，1位组法，单发两个都可以
    MSG_TYPE = '1'  # 消息类型，1为短信，2为彩信
    USERNAME = 'jrtt@zdcy'
    PASSWORD = 'tuBUE278'

    def __init__(self):
        self.username = self.USERNAME
        self.passwd = self.PASSWORD
        self.client = Client(
            self.WSDLFILE,
            transport=RequestsTransport()
        )

    def get_account_info(self):
        res = self.client.service.GetAccountInfo(self.username, self.passwd)
        return res

    def send_sms(self, phone, content, batchid):
        mtpack = {
            "uuid": batchid,
            "batchID": batchid,
            "sendType": self.SEND_TYPE,
            "msgType": self.MSG_TYPE,
            "msgs": {
                "MessageData": {
                    "Phone": phone,
                    "Content": content,
                    "vipFlag": False  # 是否是VIP号码，默认为False
                }
            },
        }
        res = self.client.service.Post(
            self.username,
            self.passwd,
            mtpack
        )
        logger.info('send sms: mtpack %s, res: %s' % (mtpack, res))
        return res

    def get_all_status(self):
        # 获取所有未取得状态的短信的发送状态
        params = {
            "account": self.username,
            "password": self.passwd,
            "PageSize": "10"
        }
        res = self.client.service.GetReport(
            **params
        )
        return res

    def get_one_status(self, batchid, mobile):
        # 获取莫一条短信的发送状态
        params = {
            "account": self.username,
            "password": self.passwd,
            "batchid": batchid,
            "mobile": mobile,
            "pageindex": "1",
            "flag": "0"
        }
        res = self.client.service.FindReport(**params)
        return res


xuanwu_sms = SmsXuanwu()
